package com.wanli.storemobile.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.wanli.storemobile.R;
import com.wanli.storemobile.base.DataCallBack;
import com.wanli.storemobile.bean.AreaListBean;
import com.wanli.storemobile.bean.BranchBrankListBean;
import com.wanli.storemobile.homepage.adapter.ChooseAreaListAdapter;
import com.wanli.storemobile.homepage.adapter.ChooseBranchListAdapter;
import com.wanli.storemobile.homepage.model.HomePageModelImpl;
import com.wanli.storemobile.homepage.model.IHomePageModel;
import com.wanli.storemobile.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Author:HWC
 */
public class ChooseBankDialog extends DialogFragment {


    @BindView(R.id.tv_provience_name)
    TextView tvProvienceName;
    @BindView(R.id.view_provience)
    View viewProvience;
    @BindView(R.id.ll_provience)
    LinearLayout llProvience;
    @BindView(R.id.tv_city_name)
    TextView tvCityName;
    @BindView(R.id.view_city)
    View viewCity;
    @BindView(R.id.ll_city)
    LinearLayout llCity;
    @BindView(R.id.tv_bank_name)
    TextView tvBankName;
    @BindView(R.id.view_bank)
    View viewBank;
    @BindView(R.id.ll_bank)
    LinearLayout llBank;
    @BindView(R.id.tv_branch_bank_name)
    TextView tvBranchBankName;
    @BindView(R.id.view_branch_bank)
    View viewBranchBank;
    @BindView(R.id.ll_branch_bank)
    LinearLayout llBranchBank;
    @BindView(R.id.recyclerView_provience)
    RecyclerView recyclerViewProvience;
    @BindView(R.id.recyclerView_city)
    RecyclerView recyclerViewCity;
    @BindView(R.id.recyclerView_bank)
    RecyclerView recyclerViewBank;
    @BindView(R.id.recyclerView_branchbank)
    RecyclerView recyclerViewBranchbank;
    @BindView(R.id.edit_bank_search)
    EditText editBankSearch;
    @BindView(R.id.view_bank_cancel)
    View viewBankCancel;
    @BindView(R.id.tv_bank_search)
    TextView tvBankSearch;
    @BindView(R.id.ll_root_bank)
    LinearLayout llRootBank;
    @BindView(R.id.edit_branch_bank_search)
    EditText editBranchBankSearch;
    @BindView(R.id.view_branch_bank_cancel)
    View viewBranchBankCancel;
    @BindView(R.id.tv_branch_bank_search)
    TextView tvBranchBankSearch;
    @BindView(R.id.ll_root_branchbank)
    LinearLayout llRootBranchbank;
    private Dialog dialog;
    private OnCallBackListener onCallBackListener;
    private Activity mActivity;
    private String provience;
    private int provienceCode;
    private String city;
    private int cityCode;
    private String bank;
    private String branchBank;
    private String unionpay;
    private IHomePageModel homePageModel = new HomePageModelImpl();
    private ChooseAreaListAdapter provienceAdapter;
    private ChooseAreaListAdapter cityAdapter;
    private ChooseAreaListAdapter bankAdapter;
    private ChooseBranchListAdapter branchBankAdapter;

    private List<AreaListBean.DataBean> provienceList = new ArrayList<>();
    private List<AreaListBean.DataBean> cityList = new ArrayList<>();
    private List<AreaListBean.DataBean> bankList = new ArrayList<>();
    private List<BranchBrankListBean.DataBean.RecordBean> branchBankList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initWindow();
        View view = inflater.inflate(R.layout.dialog_select_bank, null);
        ButterKnife.bind(this, view);
        mActivity = getActivity();
        initView();
        return view;
    }

    public static ChooseBankDialog newInstance(String provience, String city, String bank, String branchBank, String unionpay) {
        Bundle args = new Bundle();
        ChooseBankDialog fragment = new ChooseBankDialog();
        args.putString("provience", provience);
        args.putString("city", city);
        args.putString("bank", bank);
        args.putString("branchBank", branchBank);
        args.putString("unionpay", unionpay);
        fragment.setArguments(args);
        return fragment;
    }

    public void setOnCallBackListener(OnCallBackListener onCallBackListener) {
        this.onCallBackListener = onCallBackListener;
    }

    //    初始化请求
    private void initView() {
        provience = getArguments().getString("provience");
        city = getArguments().getString("city");
        bank = getArguments().getString("bank");
        branchBank = getArguments().getString("branchBank");
        unionpay = getArguments().getString("unionpay");

        provienceAdapter = new ChooseAreaListAdapter(provienceList, 1);
        cityAdapter = new ChooseAreaListAdapter(cityList, 2);
        bankAdapter = new ChooseAreaListAdapter(bankList, 4);
        branchBankAdapter = new ChooseBranchListAdapter(branchBankList);

        recyclerViewProvience.setLayoutManager(new LinearLayoutManager(mActivity));
        recyclerViewProvience.setAdapter(provienceAdapter);

        recyclerViewCity.setLayoutManager(new LinearLayoutManager(mActivity));
        recyclerViewCity.setAdapter(cityAdapter);

        recyclerViewBank.setLayoutManager(new LinearLayoutManager(mActivity));
        recyclerViewBank.setAdapter(bankAdapter);

        recyclerViewBranchbank.setLayoutManager(new LinearLayoutManager(mActivity));
        recyclerViewBranchbank.setAdapter(branchBankAdapter);


        provienceAdapter.setOnCallBackListener((name, code) -> {
            provience = name;
            tvProvienceName.setText(provience);
            requestGetCity(code);
            setDisplay(2);
        });

        cityAdapter.setOnCallBackListener((name, code) -> {
            city = name;
            tvCityName.setText(city);
            requestGetBank(bank);
            setDisplay(3);
        });

        bankAdapter.setOnCallBackListener((name, code) -> {
            bank = name;
            tvBankName.setText(bank);

            String branchName = editBranchBankSearch.getText().toString();
            requestGetBranchBankName(branchName);

            setDisplay(4);
        });

        branchBankAdapter.setOnCallBackListener((name, code) -> {
            branchBank = name;
            tvBranchBankName.setText(branchBank);
            if (onCallBackListener != null) {
                onCallBackListener.onCallBack(provience, city, bank, branchBank, code);
            }
            dismiss();
        });

        if (!TextUtils.isEmpty(provience)) {
            tvProvienceName.setText(provience);
        }
        if (!TextUtils.isEmpty(city)) {
            tvCityName.setText(city);
        }
        if (!TextUtils.isEmpty(bank)) {
            tvBankName.setText(bank);
        }
        if (!TextUtils.isEmpty(branchBank)) {
            tvBranchBankName.setText(branchBank);
        }

        editBankSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    viewBankCancel.setVisibility(View.VISIBLE);
                } else {
                    viewBankCancel.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        editBankSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String bankName = editBankSearch.getText().toString();
                    requestGetBank(bankName);
                    return true;
                }
                return false;
            }
        });
        editBranchBankSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    viewBranchBankCancel.setVisibility(View.VISIBLE);
                } else {
                    viewBranchBankCancel.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        editBranchBankSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String branchName = editBranchBankSearch.getText().toString();
                    requestGetBranchBankName(branchName);
                    return true;
                }
                return false;
            }
        });
        requestGetProvince();
    }

    public void setDisplay(int type) {
        viewProvience.setVisibility(View.INVISIBLE);
        viewCity.setVisibility(View.INVISIBLE);
        viewBank.setVisibility(View.INVISIBLE);
        viewBranchBank.setVisibility(View.INVISIBLE);

        recyclerViewProvience.setVisibility(View.GONE);
        recyclerViewCity.setVisibility(View.GONE);
        llRootBank.setVisibility(View.GONE);
        llRootBranchbank.setVisibility(View.GONE);

        if (type == 1) {
            viewProvience.setVisibility(View.VISIBLE);
            recyclerViewProvience.setVisibility(View.VISIBLE);
        }
        if (type == 2) {
            viewCity.setVisibility(View.VISIBLE);
            recyclerViewCity.setVisibility(View.VISIBLE);
        }
        if (type == 3) {
            viewBank.setVisibility(View.VISIBLE);
            llRootBank.setVisibility(View.VISIBLE);
        }
        if (type == 4) {
            viewBranchBank.setVisibility(View.VISIBLE);
            llRootBranchbank.setVisibility(View.VISIBLE);
        }
    }

    public void requestGetProvince() {
        homePageModel.requestGetProvince(new DataCallBack<AreaListBean>() {
            @Override
            public void onSuccessful(AreaListBean bean) {
                provienceList.clear();
                provienceList.addAll(bean.getData());
                provienceAdapter.notifyDataSetChanged();
                if (!TextUtils.isEmpty(provience)) {
                    for (AreaListBean.DataBean dataBean : provienceList) {
                        if (provience.equals(dataBean.getProvince_name())) {
                            provienceCode = dataBean.getProvince_code();
                            requestGetCity(dataBean.getProvince_code());
                            break;
                        }
                    }
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestGetCity(int province_code) {
        homePageModel.requestGetCity(province_code, new DataCallBack<AreaListBean>() {
            @Override
            public void onSuccessful(AreaListBean bean) {
                cityList.clear();
                cityList.addAll(bean.getData());
                cityAdapter.notifyDataSetChanged();

                if (!TextUtils.isEmpty(city)) {
                    for (AreaListBean.DataBean dataBean : cityList) {
                        if (city.equals(dataBean.getCity_name())) {
                            cityCode = dataBean.getCity_code();
                            requestGetBank(bank);
                            break;
                        }
                    }
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 总行
     *
     * @param bank_name
     */
    public void requestGetBank(String bank_name) {
        homePageModel.requestGetBankName(bank_name, new DataCallBack<AreaListBean>() {
            @Override
            public void onSuccessful(AreaListBean bean) {
                bankList.clear();
                bankList.addAll(bean.getData());
                bankAdapter.notifyDataSetChanged();
                if (!TextUtils.isEmpty(bank)) {
                    requestGetBranchBankName("");
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 支行
     */
    public void requestGetBranchBankName(String key) {
        if (TextUtils.isEmpty(provience)) {
            ToastUtil.showShort("请选择省");
            return;
        }
        if (TextUtils.isEmpty(city)) {
            ToastUtil.showShort("请选择市");
            return;
        }
        if (TextUtils.isEmpty(bank)) {
            ToastUtil.showShort("请选择总行");
            return;
        }
        homePageModel.requestGetBranchBankName(1, key, bank, provience, city, new DataCallBack<BranchBrankListBean>() {
            @Override
            public void onSuccessful(BranchBrankListBean bean) {
                if (bean.getData().getRecord().size() == 0) {
                    ToastUtil.showShort("暂无数据");
                }
                branchBankList.clear();
                branchBankList.addAll(bean.getData().getRecord());
                branchBankAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    //设置window属性
    private void initWindow() {
        //去掉dialog的标题
        dialog = this.getDialog();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        Window window = dialog.getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        window.getAttributes().windowAnimations = R.style.commomDialog;
        window.setAttributes(lp);
        window.setBackgroundDrawable(new ColorDrawable());
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @OnClick({R.id.ll_provience, R.id.ll_city, R.id.ll_bank, R.id.ll_branch_bank,
            R.id.view_bank_cancel, R.id.view_branch_bank_cancel, R.id.tv_bank_search, R.id.tv_branch_bank_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_provience:
                setDisplay(1);
                break;
            case R.id.ll_city:
                setDisplay(2);
                break;
            case R.id.ll_bank:
                setDisplay(3);
                break;
            case R.id.ll_branch_bank:
                setDisplay(4);
                break;
            case R.id.view_bank_cancel:
                editBankSearch.setText("");
                break;
            case R.id.view_branch_bank_cancel:
                editBranchBankSearch.setText("");
                break;
            case R.id.tv_bank_search:
                String bankName = editBankSearch.getText().toString();
                requestGetBank(bankName);
                break;
            case R.id.tv_branch_bank_search:
                String branchName = editBranchBankSearch.getText().toString();
                requestGetBranchBankName(branchName);
                break;
        }
    }

    public interface OnCallBackListener {
        void onCallBack(String provience, String city, String bank, String branchBank, String unionpay);
    }
}
